﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LeadChina.AssemblyLine.Common.Tcp
{
    class TcpTool
    {
        private string TcpIP { get; }
        private int TcpPort { get; }
        public int BufferSize { get; set; }
        public bool ConnectStatus { set; get; }

        public event EventHandler<byte[]> ReceiveEventHandler;
        public event EventHandler<Exception> ExceptionHandler;

        private readonly Socket socket;

        public TcpTool(string tcpIP, string tcpPort)
        {
            try
            {
                TcpIP = tcpIP;
                TcpPort = int.Parse(tcpPort);
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = 100,ReceiveTimeout = 100};
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.ToString(), "sock初始化失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void Connect()
        {
            try
            {
                socket.Connect(new IPEndPoint(IPAddress.Parse(TcpIP), TcpPort));
                byte[] bufferBytes = new byte[socket.ReceiveBufferSize];
                socket.BeginReceive(bufferBytes, 0, bufferBytes.Length, SocketFlags.None, EndReceived, bufferBytes);
                ConnectStatus = true;
            }
            catch (Exception ex)
            {
                ConnectStatus = false;
                //XtraMessageBox.Show(ex.ToString(), "sock连接化失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw ex;
            }
        }

        private void EndReceived(IAsyncResult ar)
        {
            try
            {
                byte[] recBufferBytes = (byte[])ar.AsyncState;
                int length = socket.EndReceive(ar);
                if (length > 1)
                {
                    ReceiveEventHandler?.Invoke(this, recBufferBytes);
                }
                byte[] bufferBytes = new byte[socket.ReceiveBufferSize];
                socket.BeginReceive(bufferBytes, 0, bufferBytes.Length, SocketFlags.None, EndReceived, bufferBytes);
            }
            catch (Exception ex)
            {
                ConnectStatus = false;
                ExceptionHandler?.Invoke(this, ex);
                throw ex;
            }
        }

        public void DisConnect()
        {
            try
            {
                socket.Disconnect(true);
            }
            catch (Exception ex)
            {
                ExceptionHandler?.Invoke(this, ex);
                throw ex;

            }
        }

        public void SendCommand(byte[] bufferBytes)
        {
            socket.BeginSend(bufferBytes, 0, bufferBytes.Length, SocketFlags.None, EndSended, bufferBytes);
        }

        private void EndSended(IAsyncResult ar)
        {
            try
            {
                socket.EndSend(ar);
            }
            catch (Exception ex)
            {
                ConnectStatus = false;
                ExceptionHandler?.Invoke(this, ex);
                throw ex;
            }
        }
    }
}
